package com.yawn.zerodefect.util;

import org.activiti.engine.identity.User;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;

import javax.servlet.http.HttpSession;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;

public class WebUtil {

    private WebUtil() {
    }

    public static User getUser(HttpSession session) {
        return (User) session.getAttribute("user");
    }

    public static ResponseEntity<byte[]> download(File file) throws IOException {
        try(InputStream inputStream = new FileInputStream(file)) {
            return download(inputStream, file.getName());
        }
    }

    public static ResponseEntity<byte[]> download(InputStream inputStream, String name) throws IOException {
        HttpHeaders httpHeaders = new HttpHeaders();
        httpHeaders.setContentType(MediaType.APPLICATION_OCTET_STREAM);
        byte[] bytes;
        bytes = new byte[inputStream.available()];
        inputStream.read(bytes);
        httpHeaders.setContentDispositionFormData("attachment", name);
        return new ResponseEntity<>(bytes, httpHeaders, HttpStatus.CREATED);
    }

    public static ResponseEntity<byte[]> download(byte[] bytes, String name) {
        HttpHeaders httpHeaders = new HttpHeaders();
        httpHeaders.setContentType(MediaType.APPLICATION_OCTET_STREAM);
        httpHeaders.setContentDispositionFormData("attachment", name);
        return new ResponseEntity<>(bytes, httpHeaders, HttpStatus.CREATED);
    }
}
